package cn.edu.jxau.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 编码过滤器
 * 
 * @author zclong 2017年12月13日
 */
public class CharsetEncodingFilter implements Filter {

	private String encoding;

	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * 设置编码
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		// System.out.println("CharsetEncodingFilter.doFilter()");
		// 设置字符集
		req.setCharacterEncoding(encoding);
		// System.out.println("--------doFilter begin----------");
		// 如果继续执行其他的操作，必须显示的执行如下语句
		chain.doFilter(req, resp);
		// System.out.println("--------doFilter end----------");
	}

	/**
	 * 初始化，从web.xml中获取初始化参数
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		encoding = fConfig.getInitParameter("encoding");
	}

}
